package service

import (
	"fmt"
	"zhonghui/console/warehouse/cfgx"
	"zhonghui/console/warehouse/logx"

	"github.com/ddliu/go-httpclient"
	jsoniter "github.com/json-iterator/go"
)

type UnionId2ExternalUserIdReq struct {
	UnionId     string `json:"unionid"`
	OpenId      string `json:"openid"`
	SubjectType int    `json:"subject_type"`
}

type UnionId2ExternalUserIdResponse struct {
	Errcode        int64  `json:"errcode"`
	Errmsg         string `json:"errmsg"`
	ExternalUserid string `json:"external_userid"`
	PendingId      string `json:"pending_id"`
}

type ExternalToPendingReq struct {
	ExternalUserid string `json:"external_userid"`
}

type ExternalToPendingItem struct {
	ExternalUserid string `json:"external_userid"`
	PendingId      string `json:"pending_id"`
}

type ExternalToPendingResponse struct {
	Errcode int64                   `json:"errcode"`
	Errmsg  string                  `json:"errmsg"`
	Result  []ExternalToPendingItem `json:"result"`
}

func ExternalToPending(externalUserid string, accessToken string) (*ExternalToPendingResponse, error) {
	data := &ExternalToPendingResponse{}

	body := ExternalToPendingReq{
		ExternalUserid: externalUserid,
	}

	jsonBody, err := jsoniter.MarshalToString(body)
	if err != nil {
		return nil, err
	}

	host := cfgx.Cfg().GetString("wx.host")
	url := fmt.Sprintf("%s/cgi-bin/idconvert/batch/external_userid_to_pending_id?access_token=%s", host, accessToken)

	res, err := httpclient.PostJson(url, jsonBody)
	if err != nil {
		return nil, err
	}
	ret, err := res.ToString()
	if err != nil {
		return nil, err
	}

	logx.Zap().Infow("ExternalToPending", "ret", ret)

	return data, jsoniter.UnmarshalFromString(ret, data)

}

func UnionId2ExternalUserId(unionid, openid, accessToken string, subjectType int) (*UnionId2ExternalUserIdResponse, error) {
	data := &UnionId2ExternalUserIdResponse{}

	body := UnionId2ExternalUserIdReq{
		UnionId:     unionid,
		OpenId:      openid,
		SubjectType: subjectType,
	}

	jsonBody, err := jsoniter.MarshalToString(body)
	if err != nil {
		return nil, err
	}

	host := cfgx.Cfg().GetString("wx.host")
	url := fmt.Sprintf("%s/cgi-bin/idconvert/unionid_to_external_userid?access_token=%s", host, accessToken)

	res, err := httpclient.PostJson(url, jsonBody)
	if err != nil {
		return nil, err
	}
	ret, err := res.ToString()
	if err != nil {
		return nil, err
	}

	logx.Zap().Infow("UnionId2ExternalUserId", "ret", ret)

	return data, jsoniter.UnmarshalFromString(ret, data)
}
